#!/bin/bash -e
# shellcheck source=meta-facebook/meta-minerva/recipes-minerva/plat-tool/files/minerva-common-functions
# Select UART Mux: UART Mux for switching between MTIA blade 0~15
# Usage: select-uart-mux <0-15>
source /usr/libexec/minerva-common-functions

convert_decimal_to_binary() {
    decimal=$1

    binary=""
    for ((i = 3; i >= 0; i--)); do
        bit=$(( (decimal >> i) & 1 ))
        binary="${binary}${bit}"
    done

    echo "$binary"
}

uart_mux_select()
{
    local BLADE_INDEX=$1

    if ((BLADE_INDEX >= 0)) && ((BLADE_INDEX < 16)); then
        BINARY_INDEX=$(convert_decimal_to_binary "$BLADE_INDEX")

        set_gpio BLADE_UART_SEL0 "${BINARY_INDEX:3:1}"
        set_gpio BLADE_UART_SEL1 "${BINARY_INDEX:2:1}"
        set_gpio BLADE_UART_SEL2 "${BINARY_INDEX:1:1}"
        set_gpio BLADE_UART_SEL3 "${BINARY_INDEX:0:1}"
    else
        logger -p user.info "uart_mux_select: unknow blade index ($BLADE_INDEX)"
        return 1
    fi

    return 0
}

BLADE_INDEX=$1
uart_mux_select "$BLADE_INDEX"
